package mo.tags.stack;

import mo.common.ListNode;

import java.util.ArrayDeque;
import java.util.Deque;

public class L2487 {

    public ListNode removeNodes(ListNode head) {
        Deque<ListNode> queue = new ArrayDeque<>();
        ListNode cur = head;
        while (cur != null) {
            while (!queue.isEmpty() && queue.peekLast().val < cur.val) {
                queue.pollLast();
            }
            queue.addLast(cur);
            cur = cur.next;
        }
        ListNode dummy = new ListNode(-1);
        cur = dummy;
        while (!queue.isEmpty()) {
            cur.next = queue.pollFirst();
            cur = cur.next;
        }
        return dummy.next;
    }

}
